package com.yanqu.road.message;

import com.yanqu.road.define.YanQuMessageDefine;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;

public class YanQuMessageDecrypt extends ByteToMessageDecoder {

    private static Logger logger = LogManager.getLogger(YanQuMessageDecrypt.class.getName());

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < YanQuMessageDefine.HEADER_SIZE) {
            return;
        }

        ByteBuf byteBuf = in.slice();

        short headerMark = byteBuf.readShort();
        if (headerMark != YanQuMessageDefine.HEADER_MARK) {
            byteBuf.readShort();
            return;
        }

        int msgLength = byteBuf.readInt();
        if (msgLength > in.readableBytes()) {
          //  logger.debug("msg length too long. length: " + msgLength);
            int code = byteBuf.readInt();
         //   logger.debug("msg length too long. code: " + code);
            return;
        }

        if (msgLength <= 0) {
            logger.debug("msg length too short. length:  {}",msgLength);
            return;
        }

        decrypt(in, msgLength, out);

    }

    protected void decrypt(ByteBuf in, int msgLength, List<Object> out) {
        int bodyLen = msgLength - YanQuMessageDefine.HEADER_SIZE;

        YanQuMessage yanQuMessage = new YanQuMessage();
        yanQuMessage.readHeaderNetty(in);


        if (bodyLen > 0) {
            byte[] bytes = new byte[bodyLen];
            in.readBytes(bytes, 0, bodyLen);
            yanQuMessage.setBytes(bytes);
            out.add(yanQuMessage);
        } else {
            yanQuMessage.setBytes(new byte[0]);
            out.add(yanQuMessage);
        }
    }

}
